use bevy::math::Vec2;
use bevy::prelude::KeyCode;
use rand::prelude::IndexedRandom;
use rand::Rng;
use rusty_engine::game::Engine;
use rusty_engine::LEFT;
use crate::game_state::{GameScene, GameState};
use crate::{BACKGROUND_LAYER, UI_TOP_LAYER};
use crate::scenes::switch_scene;

pub const CAR_MAX_NUM_BASE: u32 = 6;
pub const MAX_COINS: u32 = 5;
pub const COIN_SPAWN_PROB: f32 = 0.005;
pub const PLAYER_SPEED: f32 = 250.0;
pub const ROAD_SPEED: f32 = 400.0;
pub const SAFE_DISTANCE: f32 = 300.0;   // 车辆生成距离

pub const LANES: [f32; 4] = [90.0, 270.0, -90.0, -270.0];

pub const MUSIC_TRACKS: [&str; 3] = [
    "music/song_game_0.ogg",
    "music/song_game_1.ogg",
    "music/song_game_2.ogg",
];

pub const IMPACT_MUSIC_TRACKS: [&str; 3] = [
    "sfx/impact0.ogg",
    "sfx/impact1.ogg",
    "sfx/impact2.ogg",
];

// 调试模式 
pub fn debug_mode(engine: &mut Engine, game_state: &mut GameState) {
    if engine.keyboard_state.pressed_any(&[KeyCode::O]) {
        switch_scene(game_state, GameScene::MainMenu);
    } else if engine.keyboard_state.pressed_any(&[KeyCode::I]) {
        switch_scene(game_state, GameScene::GameOver);
    }
}

// 暂停显示
pub fn pause_display(engine: &mut Engine, game_state: &mut GameState) {
    if game_state.stop {
        // 显示暂停状态
        if let Some(pause_text) = engine.texts.get_mut("pause_text") {
            pause_text.value = "游戏暂停 (PAUSED)\n按P继续".to_string();
            pause_text.font = "font/HYPixel11pxU-2.ttf".to_string();
        }
        return;
    } else {
        // 隐藏暂停文本
        if let Some(pause_text) = engine.texts.get_mut("pause_text") {
            pause_text.value = "".to_string();
            pause_text.font = "font/HYPixel11pxU-2.ttf".to_string();
        }
    }
}

// 切换暂停状态
pub fn toggle_pause(engine: &mut Engine, game_state: &mut GameState) {
    game_state.stop = !game_state.stop;

    if game_state.stop {

        // 确保暂停文本存在
        if !engine.texts.contains_key("pause_text") {
            let pause_text = engine.add_text("pause_text", "游戏暂停 (PAUSED)\n按P继续");
            pause_text.translation = Vec2::new(0.0, 0.0);
            pause_text.font_size = 48.0;
            pause_text.layer = UI_TOP_LAYER + 1.0;
            pause_text.font = "font/HYPixel11pxU-2.ttf".to_string();
        }
    } else {
        // 清空暂停文本内容
        if let Some(pause_text) = engine.texts.get_mut("pause_text") {
            pause_text.value = "".to_string();
        }
    }
}

// 根据游戏进度计算动态参数
pub fn get_dynamic_params(game_state: &GameState) -> (f32, u32, f32) {

    let factor = if game_state.current_scene == GameScene::SingleGame {
        (game_state.distance[0] / 1000.0).ln_1p()
    } else {
        (f32::max(game_state.distance[0], game_state.distance[1]) / 1000.0).ln_1p()
    };

    // 生成车辆的概率(范围0.01-0.05)
    let spawn_prob = (0.01 + factor * 0.005).min(0.05);

    // 最大车辆数
    let max_cars = CAR_MAX_NUM_BASE + (factor * 2.0).round() as u32;

    // 速度增加因子 factor * 0.5 确保速度不会过快
    let speed_factor = factor * 0.5;

    (spawn_prob, max_cars, speed_factor)
}

pub fn move_cars(engine: &mut Engine, game_state: &mut GameState) {
    // 检测当前车辆的数量
    let mut cars_to_remove = Vec::new();

    // 统计现有车辆并移动它们
    for (label, sprite) in engine.sprites.iter_mut() {
        if label.starts_with("car_") {
            // 获取车辆速度
            if let Some(speed) = game_state.car_speeds.get(label) {
                if sprite.translation.y > 0.0 {
                    // 上方车道
                    sprite.rotation = LEFT;
                    sprite.translation.x -= speed * engine.delta_f32;
                } else {
                    // 下方车道
                    if game_state.current_scene == GameScene::DoubleGame {
                        sprite.rotation = LEFT;
                    }
                    sprite.translation.x -= speed * engine.delta_f32;
                }
                // 检查是否超出屏幕
                if sprite.translation.x < -800.0 || sprite.translation.x > 800.0 {
                    cars_to_remove.push(label.clone());
                }
            }
        }
    }
    // 移除超出屏幕的车辆
    for label in &cars_to_remove {
        engine.sprites.remove(label);
        game_state.car_speeds.remove(label);
    }
}

pub fn move_player(engine : &mut Engine , key : &str, speed : f32, direction : Vec2 ) {
    if let Some(player) = engine.sprites.get_mut(key) {

        // Y轴移动逻辑
        if (player.translation.y >= 330.0 && direction.y < 0.0) ||
            (player.translation.y <= -330.0 && direction.y > 0.0) ||
            (player.translation.y < 330.0 && player.translation.y > -330.0) {
            player.translation.y += direction.y * speed;
            player.rotation = direction.y * 0.15;
        }

        // X轴移动逻辑
        if (player.translation.x >= 550.0 && direction.x < 0.0) ||
            (player.translation.x <= -550.0 && direction.x > 0.0) ||
            (player.translation.x > -550.0 && player.translation.x < 550.0) {
            player.translation.x += direction.x * speed;
        }

        // Y轴边界检查
        player.translation.y = player.translation.y.clamp(-330.0, 330.0);

        // X轴边界检查
        player.translation.x = player.translation.x.clamp(-550.0, 550.0);

        // 添加旋转重置逻辑
        if direction.y == 0.0 {
            player.rotation = 0.0
        }
    }
}

pub fn move_road_elements(engine: &mut Engine) {
    for sprite in engine.sprites.values_mut() {
        if sprite.label.starts_with("roadline") {
            sprite.translation.x -= ROAD_SPEED * engine.delta_f32;
            if sprite.translation.x < -675.0 {
                sprite.translation.x += 1500.0;
            }
        }
    }
}

pub fn handle_collisions(engine: &mut Engine, game_state: &mut GameState) {

    let mut cars_to_remove = Vec::new();
    let mut coins_to_remove = Vec::new();
    let mut hearts_to_remove = Vec::new();

    for event in engine.collision_events.drain(..) {
        if event.state.is_end() {
            continue;
        }

        let label1 = &event.pair.0;
        let label2 = &event.pair.1;

        // 先处理和玩家1的碰撞
        let health_message : &str = "health_0_message";
        let coin_message: &str = "coin_0_message";
        let key = "player1";
        let index = if key == "player1" { 0 } else { 1 };

        // 玩家1与其他车辆碰撞
        if (label1 == key && label2.starts_with("car_")) ||
            (label2 == key && label1.starts_with("car_"))
        {
            // 确定碰撞的车辆标签
            let car_label = if label1.starts_with("car_") { label1 } else { label2 };

            // 记录要移除的车辆
            cars_to_remove.push(car_label.clone());

            // 如果玩家不处于无敌状态，则处理伤害
            if !game_state.hit[index] && game_state.health_amount[index] > 0 {
                let health_message = engine.texts.get_mut(health_message).unwrap();
                game_state.health_amount[index] -= 1;
                health_message.value = format!("生命值: {}", game_state.health_amount[index]);
                engine.audio_manager.play_sfx("sfx/car_impact.ogg", 0.8);

                // 添加碰撞效果（当且仅当血量为0）
                if game_state.health_amount[index] == 0 {
                    if let Some(player) = engine.sprites.get_mut(key){
                        player.rotation = 0.5;
                    }
                }

                // 切换到受击状态
                game_state.hit[index] = true;
                game_state.hit_timer[index].reset();
            }
        }
        // 玩家与金币碰撞
        else if (label1 == key && label2.starts_with("coin_")) ||
            (label2 == key && label1.starts_with("coin_"))
        {
            let coin_message = engine.texts.get_mut(coin_message).unwrap();
            // 确定碰撞的金币标签
            let coin_label = if label1.starts_with("coin_") { label1 } else { label2 };

            // 记录要移除的金币
            coins_to_remove.push(coin_label.clone());

            // 增加金币数量
            game_state.coins[index] += 1;
            coin_message.value = format!("金币数: {}", game_state.coins[index]);

            engine.audio_manager.play_sfx("sfx/eat.ogg", 1.0);
        }
        // 车辆之间的碰撞 - 将速度置为 ROAD_SPEED，即实现相对静止
        else if label1.starts_with("car_") && label2.starts_with("car_") {
            // 获取两车的速度
            game_state.car_speeds.insert(label1.clone(), ROAD_SPEED);
            game_state.car_speeds.insert(label2.clone(), ROAD_SPEED);


            // 播放碰撞音效：和玩家碰撞区分
            let random_track : &str = IMPACT_MUSIC_TRACKS
                .choose(&mut rand::rng())
                .expect("音乐列表不应为空");

            engine.audio_manager.play_sfx(random_track, 1.0);
        }
        // 玩家与爱心碰撞
        else if (label1 == key && label2.starts_with("heart_")) ||
            (label2 == key && label1.starts_with("heart_"))
        {
            // 确定碰撞的爱心标签
            let heart_label = if label1.starts_with("heart_") { label1 } else { label2 };

            // 记录要移除的爱心
            hearts_to_remove.push(heart_label.clone());

            // 增加生命值
            let health_gain = 1;
            game_state.health_amount[index] = game_state.health_amount[index] + health_gain;

            // 更新生命值显示
            let health_message = engine.texts.get_mut(health_message).unwrap();
            health_message.value = format!("生命值: {}", game_state.health_amount[index]);

            engine.audio_manager.play_sfx("sfx/eat.ogg", 1.0);
        }

        // 再处理玩家2的碰撞
        if game_state.current_scene != GameScene::DoubleGame {
            continue;
        }
        let health_message : &str = "health_1_message";
        let coin_message: &str = "coin_1_message";
        let key = "player2";
        let index = if key == "player1" { 0 } else { 1 };

        // 玩家2与其他车辆碰撞
        if (label1 == key && label2.starts_with("car_")) ||
            (label2 == key && label1.starts_with("car_"))
        {
            // 确定碰撞的车辆标签
            let car_label = if label1.starts_with("car_") { label1 } else { label2 };

            // 记录要移除的车辆
            cars_to_remove.push(car_label.clone());

            // 如果玩家不处于无敌状态，则处理伤害
            if !game_state.hit[index] && game_state.health_amount[index] > 0 {
                let health_message = engine.texts.get_mut(health_message).unwrap();
                game_state.health_amount[index] -= 1;
                health_message.value = format!("生命值: {}", game_state.health_amount[index]);
                engine.audio_manager.play_sfx("sfx/car_impact.ogg", 0.8);

                // 添加碰撞效果（当且仅当血量为0）
                if game_state.health_amount[index] == 0 {
                    if let Some(player) = engine.sprites.get_mut(key){
                        player.rotation = 0.5;
                    }
                }

                // 切换到受击状态
                game_state.hit[index] = true;
                game_state.hit_timer[index].reset();
            }
        }
        // 玩家与金币碰撞
        else if (label1 == key && label2.starts_with("coin_")) ||
            (label2 == key && label1.starts_with("coin_"))
        {
            let coin_message = engine.texts.get_mut(coin_message).unwrap();
            // 确定碰撞的金币标签
            let coin_label = if label1.starts_with("coin_") { label1 } else { label2 };

            // 记录要移除的金币
            coins_to_remove.push(coin_label.clone());

            // 增加金币数量
            game_state.coins[index] += 1;
            coin_message.value = format!("金币数: {}", game_state.coins[index]);

            engine.audio_manager.play_sfx("sfx/eat.ogg", 1.0);
        }
        // 车辆之间的碰撞 - 将速度置为 ROAD_SPEED，即实现相对静止
        else if label1.starts_with("car_") && label2.starts_with("car_") {
            // 获取两车的速度
            game_state.car_speeds.insert(label1.clone(), ROAD_SPEED);
            game_state.car_speeds.insert(label2.clone(), ROAD_SPEED);


            // 播放碰撞音效：和玩家碰撞区分
            let random_track : &str = IMPACT_MUSIC_TRACKS
                .choose(&mut rand::rng())
                .expect("音乐列表不应为空");

            engine.audio_manager.play_sfx(random_track, 1.0);
        }
        // 玩家与爱心碰撞
        else if (label1 == key && label2.starts_with("heart_")) ||
            (label2 == key && label1.starts_with("heart_"))
        {
            // 确定碰撞的爱心标签
            let heart_label = if label1.starts_with("heart_") { label1 } else { label2 };

            // 记录要移除的爱心
            hearts_to_remove.push(heart_label.clone());

            // 增加生命值
            let health_gain = 1;
            game_state.health_amount[index] = game_state.health_amount[index] + health_gain;

            // 更新生命值显示
            let health_message = engine.texts.get_mut(health_message).unwrap();
            health_message.value = format!("生命值: {}", game_state.health_amount[index]);

            engine.audio_manager.play_sfx("sfx/eat.ogg", 1.0);
        }
    }

    // 移除碰撞的车辆
    for car_label in cars_to_remove {
        engine.sprites.remove(&car_label);
        game_state.car_speeds.remove(&car_label);
    }

    // 移除收集的金币
    for coin_label in coins_to_remove {
        engine.sprites.remove(&coin_label);
    }

    // 移除收集的爱心
    for heart_label in hearts_to_remove {
        engine.sprites.remove(&heart_label);
    }

    if game_state.health_amount[0] == 0 && !game_state.lost[0] {
        game_state.lost[0] = true;
    }
    if game_state.current_scene == GameScene::DoubleGame && game_state.health_amount[1] == 0 && !game_state.lost[1] {
        game_state.lost[1] = true;
    }
}

// 生成金币
pub fn generate_coins(engine: &mut Engine) {
    // 统计当前金币数量
    let mut coin_count = 0;
    for label in engine.sprites.keys() {
        if label.starts_with("coin_") {
            coin_count += 1;
        }
    }

    // 如果金币数量不足上限，尝试生成新金币
    if coin_count < MAX_COINS && rand::rng().random_range(0.0..1.0) < COIN_SPAWN_PROB {
        // 随机选择一个车道
        let lane_idx = rand::rng().random_range(0..LANES.len());
        let lane_y = LANES[lane_idx];

        // 随机偏移量
        let y_offset = rand::rng().random_range(-40.0..40.0);
        let y_position = lane_y + y_offset;

        // 随机X位置
        let x_position = rand::rng().random_range(600.0..750.0);

        // 检查位置是否安全
        let mut safe_to_spawn = true;
        for (_, sprite) in engine.sprites.iter() {
            if sprite.label.starts_with("coin_") || sprite.label.starts_with("car_") {
                let distance = ((sprite.translation.x - x_position).powi(2) +
                    (sprite.translation.y - y_position).powi(2)).sqrt();
                if distance < 150.0 {
                    safe_to_spawn = false;
                    break;
                }
            }
        }

        if safe_to_spawn {
            // 创建金币精灵
            let coin_id = format!("coin_{}", rand::random::<u32>());
            let coin = engine.add_sprite(&coin_id, "sprite/coin/coin.png");
            coin.translation.x = x_position;
            coin.translation.y = y_position;
            coin.scale = 0.2;
            coin.layer = BACKGROUND_LAYER;
            coin.collision = true;
        }
    }
}

// 移动金币
pub fn move_coins(engine: &mut Engine) {
    let mut coins_to_remove = Vec::new();

    for (label, sprite) in engine.sprites.iter_mut() {
        if label.starts_with("coin_") {
            // 金币以道路速度向左移动
            sprite.translation.x -= ROAD_SPEED * engine.delta_f32;

            // 检查是否超出屏幕左侧
            if sprite.translation.x < -800.0 {
                coins_to_remove.push(label.clone());
            }
        }
    }

    // 移除超出屏幕的金币
    for coin_label in coins_to_remove {
        engine.sprites.remove(&coin_label);
    }
}


// 生成爱心
pub fn generate_hearts(engine: &mut Engine, game_state: &mut GameState) {
    // 计算爱心应该生成的数量
    let expected_hearts = (game_state.distance[0] / 1000.0) as u32;

    // 如果当前生成的爱心的数量小于应该生成的数量
    if game_state.hearts_cnt < expected_hearts {
        // 统计当前存在的爱心数量
        let mut existing_hearts = 0;
        for label in engine.sprites.keys() {
            if label.starts_with("heart_") {
                existing_hearts += 1;
            }
        }

        // 同时只允许1颗爱心存在
        if existing_hearts == 0 {
            // 随机选择一个车道
            let lane_idx = rand::rng().random_range(0..LANES.len());
            let lane_y = LANES[lane_idx];

            // 随机偏移量
            let y_offset = rand::rng().random_range(-40.0..40.0);
            let y_position = lane_y + y_offset;

            // 随机X位置（在屏幕右侧）
            let x_position = rand::rng().random_range(600.0..750.0);

            // 检查位置是否安全
            let mut safe_to_spawn = true;
            for (_, sprite) in engine.sprites.iter() {
                // 检查与车辆、金币和其他爱心的距离
                if sprite.label.starts_with("coin_") ||
                    sprite.label.starts_with("car_") ||
                    sprite.label.starts_with("heart_")
                {
                    let distance = ((sprite.translation.x - x_position).powi(2) +
                        (sprite.translation.y - y_position).powi(2)).sqrt();
                    if distance < 200.0 { // 更长的安全距离
                        safe_to_spawn = false;
                        break;
                    }
                }
            }

            if safe_to_spawn {
                // 创建爱心精灵
                let heart_id = format!("heart_{}", rand::random::<u32>());
                let heart = engine.add_sprite(&heart_id, "sprite/heart/heart.png");
                heart.translation.x = x_position;
                heart.translation.y = y_position;
                heart.scale = 0.2;
                heart.layer = BACKGROUND_LAYER;
                heart.collision = true;

                // 记录爱心已生成
                game_state.hearts_cnt += 1;
            }
        }
    }
}

// 移动爱心
pub fn move_hearts(engine: &mut Engine) {
    let mut hearts_to_remove = Vec::new();

    for (label, sprite) in engine.sprites.iter_mut() {
        if label.starts_with("heart_") {
            // 爱心以道路速度向左移动
            sprite.translation.x -= ROAD_SPEED * engine.delta_f32;

            // 检查是否超出屏幕左侧
            if sprite.translation.x < -800.0 {
                hearts_to_remove.push(label.clone());
            }
        }
    }

    // 移除超出屏幕的爱心
    for heart_label in hearts_to_remove {
        engine.sprites.remove(&heart_label);
    }
}